package com.braveman.im.ui.activity.message;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.braveman.im.R;
import com.braveman.im.bean.LoginBean;
import com.braveman.im.constant.Constants;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.ui.activity.HomeActivity;
import com.braveman.im.utils.UtilsStyle;
import com.ht.baselibs.application.HTApplication;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.vondear.rxtools.RxBarTool;

import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {
    private CheckBox mSeePwdView;
    private EditText mPwdEditText;
    private EditText mTelView;
    private ProgressDialog mDialog;
    private UMShareAPI umShareAPI;
    private String userName;
    private String passWord;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("登录");
    }

    @Override
    protected boolean isFulleScreen() {
        return true;
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_login;
    }

    @Override
    protected void initChildView() {
        mTelView = (EditText) findViewById(R.id.et_activity_register_tel);
        mPwdEditText = (EditText) findViewById(R.id.et_activity_register_pwd);
        mSeePwdView = (CheckBox) findViewById(R.id.cb_activity_register_see_pwd);
    }

    @Override
    protected void initChildData() {
        if (HTApplication.IS_DEBUG_MODE) {
            mTelView.setText(TextUtils.isEmpty(userName) ? "15264880523" : userName);
            mPwdEditText.setText(TextUtils.isEmpty(passWord) ? "123456" : passWord);
        } else {
            mTelView.setText(TextUtils.isEmpty(userName) ? "" : userName);
            mPwdEditText.setText(TextUtils.isEmpty(passWord) ? "" : passWord);
        }


    }

    @Override
    protected void initIntentData(Intent callIntent) {
        userName = callIntent.getStringExtra("userName");
        passWord = callIntent.getStringExtra("passWord");
    }

    @Override
    protected void setChildViewListener() {
        mSeePwdView.setOnClickListener(this);
        findViewById(R.id.tv_activity_login_register).setOnClickListener(this);
        findViewById(R.id.btn_activity_login).setOnClickListener(this);
        findViewById(R.id.tv_go_login_qq).setOnClickListener(this);
        findViewById(R.id.tv_go_login_weixin).setOnClickListener(this);
        findViewById(R.id.tv_press_login).setOnClickListener(this);
        findViewById(R.id.tv_activity_change_pwd).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        final String tel = mTelView.getText().toString();
        String pwd = mPwdEditText.getText().toString();
        switch (v.getId()) {
            case R.id.tv_activity_login_register:
                ActivityUtils.startActivity(this, RegisterActivity.class);
                break;
            case R.id.cb_activity_register_see_pwd:
                if (mSeePwdView.isChecked()) {
                    mPwdEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mPwdEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                try {
                    mPwdEditText.requestFocus();
                    mPwdEditText.setSelection(pwd.length());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_activity_login:
                if (TextUtils.isEmpty(tel)) {
                    UIUtils.showToast("请输入手机号");
                    return;
                }

                if (TextUtils.isEmpty(pwd)) {
                    UIUtils.showToast("请输入密码");
                    return;
                }
                LoginBean loginBean = new LoginBean();
                loginBean.identifier = tel;
                loginBean.identityType = "mobile";
                loginBean.password = pwd;
                showLoadingDialog();
                ApiManager.getApi().login(loginBean).enqueue(new NetCallBack<LoginBean>() {
                    @Override
                    protected void onSuccess(Call<LoginBean> call, Response<LoginBean> response) {
                        LoginBean loginBean1 = response.body();
                        SharedPreferencesUtils.put(Constants.TOKEN, loginBean1.token);
                        UIUtils.showToast("服务器登录成功");
                        signIn(loginBean1.imUsername);

                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
                break;
            case R.id.tv_go_login_qq:
                UIUtils.showToast("内测阶段，暂不开放");
//                umShareAPI = UMShareAPI.get(this);
//                SHARE_MEDIA platform = SHARE_MEDIA.QQ;
//                umShareAPI.doOauthVerify(this, platform, umAuthListener);
                break;
            case R.id.tv_go_login_weixin:
                UIUtils.showToast("内测阶段，暂不开放");
                umShareAPI = UMShareAPI.get(this);
                SHARE_MEDIA platform1 = SHARE_MEDIA.WEIXIN;
                umShareAPI.doOauthVerify(this, platform1, umAuthListener1);
                break;
            case R.id.tv_press_login:
                ActivityUtils.startActivity(LoginActivity.this, HomeActivity.class);
                break;
            case R.id.tv_activity_change_pwd:
                ActivityUtils.startActivity(LoginActivity.this, ResetPwdActivity.class);
                break;
        }
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    private UMAuthListener umAuthListener1 = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 登录方法
     */
    private void signIn(String id) {

        if (EMClient.getInstance().isLoggedInBefore()) {
            UIUtils.showToast("环信登录成功");
            SharedPreferencesUtils.put("isLogin", true);
            ActivityUtils.startActivity(LoginActivity.this, HomeActivity.class);
            return;
        }

        mDialog = new ProgressDialog(this);
        mDialog.setMessage("正在登陆环信，请稍后...");
        mDialog.show();
        String username = mTelView.getText().toString().trim();
        String password = mPwdEditText.getText().toString().trim();
        EMClient.getInstance().login(id, password, new EMCallBack() {
            /**
             * 登陆成功的回调
             */
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDialog.dismiss();
                        UIUtils.showToast("环信登录成功");
                        SharedPreferencesUtils.put("isLogin", true);
                        ActivityUtils.startActivity(LoginActivity.this, HomeActivity.class);
                    }
                });
            }

            /**
             * 登陆错误的回调
             * @param i
             * @param s
             */
            @Override
            public void onError(final int i, final String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDialog.dismiss();
                        Log.d("lzan13", "登录失败 Error code:" + i + ", message:" + s);
                        /**
                         * 关于错误码可以参考官方api详细说明
                         * http://www.easemob.com/apidoc/android/chat3.0/classcom_1_1hyphenate_1_1_e_m_error.html
                         */
                        switch (i) {
                            // 网络异常 2
                            case EMError.NETWORK_ERROR:
                                Toast.makeText(LoginActivity.this, "网络错误 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 无效的用户名 101
                            case EMError.INVALID_USER_NAME:
                                Toast.makeText(LoginActivity.this, "无效的用户名 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 无效的密码 102
                            case EMError.INVALID_PASSWORD:
                                Toast.makeText(LoginActivity.this, "无效的密码 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 用户认证失败，用户名或密码错误 202
                            case EMError.USER_AUTHENTICATION_FAILED:
                                Toast.makeText(LoginActivity.this, "用户认证失败，用户名或密码错误 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 用户不存在 204
                            case EMError.USER_NOT_FOUND:
                                Toast.makeText(LoginActivity.this, "用户不存在 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 无法访问到服务器 300
                            case EMError.SERVER_NOT_REACHABLE:
                                Toast.makeText(LoginActivity.this, "无法访问到服务器 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 等待服务器响应超时 301
                            case EMError.SERVER_TIMEOUT:
                                Toast.makeText(LoginActivity.this, "等待服务器响应超时 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 服务器繁忙 302
                            case EMError.SERVER_BUSY:
                                Toast.makeText(LoginActivity.this, "服务器繁忙 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            // 未知 Server 异常 303 一般断网会出现这个错误
                            case EMError.SERVER_UNKNOWN_ERROR:
                                Toast.makeText(LoginActivity.this, "未知的服务器异常 code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                            default:
                                Toast.makeText(LoginActivity.this, "ml_sign_in_failed code: " + i + ", message:" + s, Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                });
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

}
